package com.untour.im.server.handler;

import com.alibaba.fastjson2.JSON;
import com.untour.im.codec.protocol.packet.request.body.LoginRequestPacketData;
import com.untour.im.codec.protocol.packet.response.ResponsePacketCodec;
import com.untour.im.server.service.LoginService;
import com.untour.im.server.service.UserChannelService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacketData> {
    private LoginService loginService;
    private UserChannelService userChannelService;

    public LoginRequestHandler(LoginService loginService,UserChannelService userChannelService) {
        this.loginService = loginService;
        this.userChannelService = userChannelService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacketData msg) throws Exception {
        log.info("接受到客户端登录：{}", JSON.toJSONString(msg));
        //解析token，获取userid
        String userId = this.checkTokenAndGetUserInfo(msg);
        //保存连接信息
        userChannelService.saveUserChannel(ctx,userId,msg.getHeader());
        //发送登录应答报文
        ResponsePacketCodec.INSTANCE.sendLoginResponseMessage(ctx,msg.getMessageBody().getMessageId());

    }

    /**
     * 解析token，获取userid
     * @param packetData
     * @return
     */
    private String checkTokenAndGetUserInfo(LoginRequestPacketData packetData){
        //todo 验证token&获取用户信息
        return loginService.checkTokenAndGetUserInfo(packetData.getMessageBody().getMessageContent().getToken());
    }
}
